package com.sihai.core.support;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;

public class StringArrayUserType implements UserType {

	private static String SPLITTER = ";";

	@Override
	public Object assemble(Serializable cached, Object owner) throws HibernateException {
		return cached;
	}

	@Override
	public Object deepCopy(Object value) throws HibernateException {
		return value;
	}

	@Override
	public Serializable disassemble(Object value) throws HibernateException {
		return (Serializable) value;
	}

	@Override
	public boolean equals(Object x, Object y) throws HibernateException {
		return x == y;
	}

	@Override
	public int hashCode(Object x) throws HibernateException {
		return x.hashCode();
	}

	@Override
	public boolean isMutable() {
		return false;
	}

	@Override
	public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
		String value = (String) Hibernate.STRING.nullSafeGet(rs, names[0]);
		return value != null ? value.split(SPLITTER) : org.apache.commons.lang.ArrayUtils.EMPTY_STRING_ARRAY;
	}

	@Override
	public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
		String _val = null;
		if (value != null && value instanceof String[]) {
			String[] _array = (String[]) value;
			if (_array.length != 0) {
				StringBuilder val = new StringBuilder();
				for (int i = 0; i < _array.length; i++) {
					if (StringUtils.isNotEmpty(_array[i])) {
						val.append(_array[i]);
						if (i != (_array.length - 1))
							val.append(SPLITTER);
					}
				}
				_val = val.toString();
			}
		}
		Hibernate.STRING.nullSafeSet(st, _val, index);
	}

	@Override
	public Object replace(Object original, Object target, Object owner) throws HibernateException {
		return original;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Class returnedClass() {
		return String[].class;
	}

	@Override
	public int[] sqlTypes() {
		return new int[] { Types.VARCHAR };
	}

}
